package com.rickpan.controller;

import com.rickpan.dto.common.ApiResponse;
import com.rickpan.service.StorageRepairService;
import com.rickpan.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 存储空间修复控制器
 * 用于修复存储空间统计不一致的问题
 */
@RestController
@RequestMapping("/api/storage/repair")
public class StorageRepairController {

    private static final Logger logger = LoggerFactory.getLogger(StorageRepairController.class);

    @Autowired
    private StorageRepairService storageRepairService;

    /**
     * 修复当前用户的存储空间统计
     * POST /api/storage/repair/current-user
     */
    @PostMapping("/current-user")
    public ResponseEntity<ApiResponse<Map<String, Object>>> repairCurrentUserStorage() {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            logger.info("用户 {} 请求修复存储空间统计", userId);
            
            Map<String, Object> result = storageRepairService.repairUserStorageUsage(userId);
            
            return ResponseEntity.ok(ApiResponse.success("存储空间统计修复完成", result));
            
        } catch (Exception e) {
            logger.error("修复存储空间统计失败", e);
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("修复失败: " + e.getMessage()));
        }
    }

    /**
     * 修复所有用户的存储空间统计（管理员功能）
     * POST /api/storage/repair/all-users
     */
    @PostMapping("/all-users")
    public ResponseEntity<ApiResponse<Map<String, Object>>> repairAllUsersStorage() {
        try {
            logger.info("管理员请求修复所有用户存储空间统计");
            
            Map<String, Object> result = storageRepairService.repairAllUsersStorageUsage();
            
            return ResponseEntity.ok(ApiResponse.success("所有用户存储空间统计修复完成", result));
            
        } catch (Exception e) {
            logger.error("修复所有用户存储空间统计失败", e);
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("修复失败: " + e.getMessage()));
        }
    }

    /**
     * 检查当前用户存储空间统计是否正确
     * GET /api/storage/repair/check-current-user
     */
    @GetMapping("/check-current-user")
    public ResponseEntity<ApiResponse<Map<String, Object>>> checkCurrentUserStorage() {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            logger.info("用户 {} 检查存储空间统计", userId);
            
            Map<String, Object> result = storageRepairService.checkUserStorageUsage(userId);
            
            return ResponseEntity.ok(ApiResponse.success("存储空间统计检查完成", result));
            
        } catch (Exception e) {
            logger.error("检查存储空间统计失败", e);
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("检查失败: " + e.getMessage()));
        }
    }
}
